import api from '@/store/api';
import i18n from '@/i18n';
const { t } = i18n.global as any;

const transferProtocolType = {
  CIFS: 'CIFS',
  FTP: 'FTP',
  SFTP: 'SFTP',
  HTTP: 'HTTP',
  HTTPS: 'HTTPS',
  NFS: 'NFS',
  SCP: 'SCP',
  TFTP: 'TFTP',
  OEM: 'OEM',
};

export const useVirtualMediaStore = defineStore('virtualMedia', () => {
  const proxyDevices = ref([] as any[]);
  const legacyDevices = ref([] as any[]);
  const connections = ref([] as any[]);

  const setProxyDevicesData = (deviceData: any) =>
    (proxyDevices.value = deviceData);
  const setLegacyDevicesData = (deviceData: any) =>
    (legacyDevices.value = deviceData);

  const getData = async () => {
    const virtualMediaListEnabled =
      import.meta.env.VUE_APP_VIRTUAL_MEDIA_LIST_ENABLED === 'true'
        ? true
        : false;
    let webDevice: boolean | { [index: string]: any } = false;
    webDevice = {
      id: t('pageVirtualMedia.defaultDeviceName'),
      websocket: '/vm/0/0',
      file: null,
      transferProtocolType: transferProtocolType.OEM,
      isActive: false,
    };
    if (!virtualMediaListEnabled) {
      setProxyDevicesData([webDevice]);
      return;
    }

    return await api
      .get('/redfish/v1/Managers/bmc/VirtualMedia')
      .then((response) =>
        response.data.Members.map(
          (virtualMedia: { [x: string]: any }) => virtualMedia['@odata.id'],
        ),
      )
      .then((devices) =>
        api.all(devices.map((device: string) => api.get(device))),
      )
      .then((devices: any) => {
        const deviceData = devices.map(
          (device: {
            data: {
              Inserted: boolean;
              Id: any;
              TransferProtocolType: any;
              Oem: { OpenBMC: { WebSocketEndpoint: any } };
            };
          }) => {
            const isActive = device.data?.Inserted === true ? true : false;
            return {
              id: device.data?.Id,
              transferProtocolType: device.data?.TransferProtocolType,
              websocket: device.data?.Oem?.OpenBMC?.WebSocketEndpoint,
              isActive: isActive,
            };
          },
        );
        const proxyDevices = deviceData
          .filter(
            (d: { transferProtocolType: string }) =>
              d.transferProtocolType === transferProtocolType.OEM,
          )
          .map((device: any[]) => {
            return {
              ...device,
              file: null,
            };
          });
        const legacyDevices = deviceData
          .filter(
            (d: { transferProtocolType: string }) =>
              d.transferProtocolType !== transferProtocolType.OEM,
          )
          .map((device: any) => {
            return {
              ...device,
              serverUri: '',
              username: '',
              password: '',
              isRW: false,
            };
          });
        setProxyDevicesData([...proxyDevices, webDevice]);
        setLegacyDevicesData(legacyDevices);
      })
      .catch((error) => {
        setProxyDevicesData([webDevice]);
        console.log('Virtual Media:', error);
      });
  };
  const mountImage = async ({ id, data }: any) => {
    return await api
      .post(
        `/redfish/v1/Managers/bmc/VirtualMedia/${id}/Actions/VirtualMedia.InsertMedia`,
        data,
        undefined,
      )
      .catch((error) => {
        console.log('Mount image:', error);
        throw new Error();
      });
  };
  const unmountImage = async (id: any) => {
    return await api
      .post(
        `/redfish/v1/Managers/bmc/VirtualMedia/${id}/Actions/VirtualMedia.EjectMedia`,
        undefined,
        undefined,
      )
      .catch((error) => {
        console.log('Unmount image:', error);
        throw new Error();
      });
  };

  return {
    proxyDevices,
    legacyDevices,
    connections,
    setProxyDevicesData,
    setLegacyDevicesData,
    getData,
    mountImage,
    unmountImage,
  };
});
